﻿using Awsc.DataAcquisitionSys.Core.Models.POCO;

namespace Awsc.DataAcquisitionSys.Core.Databases
{
    public interface IWearPartRepository
    {
        Task<int> UpdateUsageAsync(int partId, double usage);
        Task<int> UpdateFactoryParameterAsync(int partId, double factoryParameter);

        Task<int> AddWearPartAsync(WearPart wearPart);
        Task<IEnumerable<WearPart>> GetAllWearPartsAsync();


    }

    public class WearPartRepository:IWearPartRepository
    {
        private readonly SQLiteHelper _dbHelper;

        public WearPartRepository(SQLiteHelper dbHelper)
        {
            this._dbHelper = dbHelper;
            InitializeDatabase();
        }

        public async Task<int> AddWearPartAsync(WearPart wearPart)
        {
            return await _dbHelper.InsertAsync(wearPart);
        }

        public async Task<IEnumerable<WearPart>> GetAllWearPartsAsync()
        {
            return await _dbHelper.QueryAsync<WearPart>("SELECT * FROM WearParts");
        }

        public async Task<int> UpdateFactoryParameterAsync(int partId, double factoryParameter)
        {
            var sql = "Update WearParts set FactoryCount=@FactoryCount where Id=@partId";
            return await _dbHelper.ExecuteNonQueryAsync(sql, new Dictionary<string, object>() { { "FactoryCount", factoryParameter }, { "partId", partId } });
        }

        public async Task<int> UpdateUsageAsync(int partId, double usage)
        {
            var sql = "Update WearParts set UsageCount=@UsageCount where Id=@partId";
            return await _dbHelper.ExecuteNonQueryAsync(sql, new Dictionary<string, object>() { { "UsageCount", usage }, { "partId", partId } });
        }

        private void InitializeDatabase()
        {
            // 创建任务元数据表
            var sql = @"
            CREATE TABLE IF NOT EXISTS WearPart (
                ID INTEGER PRIMARY KEY AUTOINCREMENT,
                Name TEXT NOT NULL,
                Description TEXT,
                Status INTEGER,
                LastMaintenanceDate TEXT,
                UsageCount Real,
                FactoryCount Real,
                CreateTime TEXT,
                UpdateTime TEXT
            );
            
            PRAGMA journal_mode = WAL;
            PRAGMA synchronous = NORMAL;
            PRAGMA cache_size = -10000; -- 10MB cache
            PRAGMA temp_store = MEMORY;
            PRAGMA busy_timeout = 3000;";
            _dbHelper.CreateTableAsync(sql).ConfigureAwait(false).GetAwaiter().GetResult();

        }




    }

}
